import redis


class RedisClient:

    # 初始化 Redis 连接
    def __init__(self, host='localhost', port=6379, db=0, password=None):
        self.client = redis.StrictRedis(host=host, port=port, db=db, password=password, decode_responses=True)

    # 设置 k-v
    def set(self, key, value, expire=None):
        self.client.set(key, value, ex=expire)

    # 获取键的值
    def get(self, key):
        return self.client.get(key)

    # 删除键
    def delete(self, key):
        self.client.delete(key)

    # 检查键是否存在
    def exists(self, key):
        return self.client.exists(key)

    # 对键的值执行递增操作
    def incr(self, key, amount=1):
        return self.client.incr(key, amount)

    # 对键的值执行递减操作
    def decr(self, key, amount=1):
        return self.client.decr(key, amount)

    # 向列表左侧插入值
    def lpush(self, key, *values):
        self.client.lpush(key, *values)

    # 向列表右侧插入值
    def rpush(self, key, *values):
        self.client.rpush(key, *values)

    # 获取列表中的元素
    def lrange(self, key, start=0, end=-1):
        """"""
        return self.client.lrange(key, start, end)

    # 向 Redis 频道发布消息
    def publish(self, channel, _message):
        self.client.publish(channel, _message)

    # 订阅 Redis 频道
    def subscribe(self, channel):
        _pubsub = self.client.pubsub()
        _pubsub.subscribe(channel)
        return _pubsub
